import {Component, Input} from '@angular/core';
import {
    ActionSheetController,
    AlertController, App, LoadingController, NavController, NavParams, Platform,
    ToastController
} from 'ionic-angular';
import {Log} from "../../../../framework/utils/Log";
import {SystemService} from "../../../service/SystemService";
import {BasePage} from "../../../BasePage";
import {UserManager} from "../../../../framework/manager/UserManager";
import {Camera, CameraOptions} from '@ionic-native/camera';
import {ImagePicker,ImagePickerOptions} from "@ionic-native/image-picker";
import {HomePage} from "../../../home/home";
import {TabsPage} from "../../../tabs/tabs";
import {ToDoApprovalPage} from "../../../home/to-do-approval/to-do-approval";

/**
 * Generated class for the ApprovePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@Component({
    selector: 'page-zjApprove',
    templateUrl: 'zjApprove.html',
    providers: [SystemService]
})
export class ZjApprovePage extends BasePage {
    spType: any;
    private static TAG: string = 'ZjApprovePage';
    @Input() detail: any;
    _d:any;
    @Input() yaosuList: any;
    remarkVal: string='';
    list: Array<any> = [];
    userId: string;
    branchId: string;
    @Input() applyFee: string;
    @Input() danJuType: string;
    private fileList: any = [];
    private fuJianList:any=[];
    private approveList:any=[];
    private checkType:any;
    private way:string;
    private valBool:boolean=false;
    private detailsInfo:any;
    private isHQBool:boolean=false;
    private hqName:any='';
    private hqId:any=[];
    private ShiFouCGJH:any='';
    private ShiFouCGJHLabel:any='';
    private ShiFouCGXG:any='';
    private ShiFouZFCG:any='';
    private ShiFouZFCGLabel:any='';
    private ShiFouKN:any='';
    private ShiFouKNLabel:any='';
    private ShiFouQDHT:any='';
    private ShiFouQDHTLabel:any='';
    private CaiGouLX:any='';
    private CaiGouLXLabel:any='';
    private CaiGouFS:any='';
    private CaiGouFSLabel:any='';
    private ZuZhiXS:any='';
    private ZuZhiXSLabel:any='';
    private cglxlist:any=[];
    private cgfslist:any=[];
    private zzxslist:any=[];
    private sflist:any=[];
    constructor(public navCtrl: NavController, public navParams: NavParams, public sys: SystemService,
                public platform: Platform,
                public loadingCtrl: LoadingController,
                private actionSheetCtrl: ActionSheetController,
                public camera: Camera,
                public imagePicker: ImagePicker,
                public toastCtrl: ToastController,
                public alertCtrl: AlertController,

                public app:App) {
        super(platform, loadingCtrl, toastCtrl, alertCtrl,);
        this.userId = UserManager.getInstance().user.userId;
        this.checkType=JSON.parse(localStorage.getItem('checkType'));
        this.detail = this.navParams.data.data;
        this.branchId = this.detail.DanJuXX.ShenQingBMBH;
        this._d = this.navParams.data._d;
        this.yaosuList=  this.detail.YaoSuXX;
        this.spType =this.navParams.data.spType;
    }

    async ngOnInit() {
        Log.printObj(ZjApprovePage.TAG, 'detailInfo', this.detail);
        Log.printObj(ZjApprovePage.TAG, '要素列表==', this.yaosuList);
        if( this.detail.DanJuXX.hqList && this.detail.DanJuXX.hqList.length>0){
            this.isHQBool = true;
            this.approveList = this.detail.DanJuXX.hqList;
        }
        if( this.spType =="2"){
            this.cglxlist = this.detail.DanJuXX.cglxlist;
            this.cgfslist = this.detail.DanJuXX.cgfslist;
            this.zzxslist = this.detail.DanJuXX.zzxslist;
            this.sflist = this.detail.DanJuXX.sflist;


            this.ShiFouCGXG = this.detail.DanJuXX.ShiFouCGXG;
            this.ShiFouZFCG = this.detail.DanJuXX.ShiFouZFCG;
            this.CaiGouLX = this.detail.DanJuXX.CaiGouLX;
            this.CaiGouFS = this.detail.DanJuXX.CaiGouFS;
            this.ShiFouCGJH = this.detail.DanJuXX.ShiFouCGJH;
            this.ZuZhiXS = this.detail.DanJuXX.ZuZhiXS;
            this.ShiFouQDHT = this.detail.DanJuXX.ShiFouQDHT;
            this.ShiFouKN = this.detail.DanJuXX.ShiFouKN;


            this.CaiGouLXLabel= this.indexToVal( this.cglxlist,this.CaiGouLX).length>0? this.indexToVal( this.cglxlist,this.CaiGouLX)[0].Zhi : ''
            this.CaiGouFSLabel= this.indexToVal( this.cgfslist,this.CaiGouFS).length>0 ? this.indexToVal( this.cgfslist,this.CaiGouFS)[0].Zhi: ''
            this.ZuZhiXSLabel=  this.indexToVal( this.zzxslist,this.ZuZhiXS).length>0? this.indexToVal( this.zzxslist,this.ZuZhiXS)[0].Zhi:''
            this.ShiFouCGJHLabel=  this.indexToVal( this.sflist,this.ShiFouCGJH).length> 0? this.indexToVal( this.sflist,this.ShiFouCGJH)[0].Zhi :'';
            this.ShiFouZFCGLabel= this.indexToVal( this.sflist,this.ShiFouZFCG).length>0? this.indexToVal( this.sflist,this.ShiFouZFCG)[0].Zhi:''
            this.ShiFouQDHTLabel=  this.indexToVal( this.sflist,this.ShiFouQDHT).length>0 ? this.indexToVal( this.sflist,this.ShiFouQDHT)[0].Zhi:''
            this.ShiFouKNLabel=  this.indexToVal( this.sflist,this.ShiFouKN).length>0? this.indexToVal( this.sflist,this.ShiFouKN)[0].Zhi:''
        }
        this.yaosuList.map((v, i) => {
            this.list.push({
                YaoSuBH: v.BianHao,
                YaoSuZ: []
            });
        })
    }

    isValNull(){
        for(let i=0; i<this.list.length;i++){
            if(this.list[i].YaoSuZ.length==0){
                this.showError("要素审批值不能为空");
                this.valBool=true;
                break;
            }
        }
        return this.valBool;
    }
    /**
     * 信息审批
     */
    getCheckInfo( _v) {
        this.valBool=false;
        if(_v=='pass'){
            this.remarkVal =this.remarkVal==""?"同意":this.remarkVal;
            if(this.isValNull()) return;
        }else {
            if(this.remarkVal=="" || this.remarkVal == undefined){
                this.showError("审核意见不能为空！");
                return;
            }
            //this.isValNull();
        }

        this.way=_v;
        if(this.isHQBool  && this.hqId.length==0){
            this.showError("会签人不能为空！");
            return
        }
        if( this.spType =="2"){
            this.zxspInfo(_v);
        }else if(this.spType =="3"){
            this.zjspInfo(_v)
        }else if(this.spType =="4"){
            this.cgInfo(_v)
        }else if(this.spType =="5"){
            this.htqdInfo(_v)
        }else if(this.spType =="6"){
            this.htbgInfo(_v)
        }

    }
    htqdInfo(_v){
        this.showLoading(true,'正在处理中');
        let data: any = {
            YongHuBH: this.userId,
            ShenQingBMBH: this.branchId,
            HeTongJE: this.detail.DanJuXX.HeTongJE==''?'0':this.detail.DanJuXX.HeTongJE,
            //DanJuLX: this.detail.DanJuXX.JieKuanDLX,
            DanJuBH: this._d.BianHao,
            LiuChengId: this._d.LiuChengId,
            TaskId: this._d.RenWuID,
            DangQianJD: this._d.DangQianJD,
            Next: _v,
            ShenPiYJ: this.remarkVal,
            FileList: this.fileList[0],
            ShenPiYS: this.list,
            sign:this.hqId.toString()
        };
        this.sys.htgldbspApprove(data).subscribe((res: any) => {
            if (res.msgCode == '1') {
                this.toastResult('审核成功','退回成功');
                //this.app.getRootNav().setRoot(ToDoApprovalPage);
                //this.navCtrl.pop();
                this.app.getRootNav().setRoot(TabsPage);

            } else {
                this.toastResult('审核失败','退回失败');
            }
            this.showLoading(false,'正在处理中');
        }, error => {
            this.toastResult('审核失败','退回失败');
            this.showLoading(false,'正在处理中');

        })
    }
    htbgInfo(_v){
        this.showLoading(true,'正在处理中');
        let data: any = {
            YongHuBH: this.userId,
            ShenQingBMBH: this.branchId,
            BaoXiaoJE: this.detail.DanJuXX.HeTongJE==''?'0':this.detail.DanJuXX.HeTongJE,
            DanJuLX: this.detail.DanJuXX.JieKuanDLX,
            DanJuBH: this._d.BianHao,
            LiuChengId: this._d.LiuChengId,
            TaskId: this._d.RenWuID,
            DangQianJD: this._d.DangQianJD,
            Next: _v,
            ShenPiYJ: this.remarkVal,
            FileList: this.fileList[0],
            ShenPiYS: this.list,
            sign:this.hqId.toString()
        };
        this.sys.htgldbspBgapprove(data).subscribe((res: any) => {
            if (res.msgCode == '1') {
                this.toastResult('审核成功','退回成功');
                //this.app.getRootNav().setRoot(ToDoApprovalPage);
                //this.navCtrl.pop();
                this.app.getRootNav().setRoot(TabsPage);

            } else {
                this.toastResult('审核失败','退回失败');
            }
            this.showLoading(false,'正在处理中');
        }, error => {
            this.toastResult('审核失败','退回失败');
            this.showLoading(false,'正在处理中');

        })
    }
    cgInfo(_v){
        this.showLoading(true,'正在处理中');
        let data: any = {
            YongHuBH: this.userId,
            ShenQingBMBH: this.branchId,
            CaiGouJE: this.detail.DanJuXX.CaiGouJE==''?'0':this.detail.DanJuXX.CaiGouJE,
            //DanJuLX: this.detail.DanJuXX.JieKuanDLX,
            DanJuBH: this._d.BianHao,
            LiuChengId: this._d.LiuChengId,
            TaskId: this._d.RenWuID,
            DangQianJD: this._d.DangQianJD,
            Next: _v,
            ShenPiYJ: this.remarkVal,
            FileList: this.fileList[0],
            ShenPiYS: this.list,
            sign:this.hqId.toString()
        };
        this.sys.cgxqdbspApprove(data).subscribe((res: any) => {
            if (res.msgCode == '1') {
                this.toastResult('审核成功','退回成功');
                //this.app.getRootNav().setRoot(ToDoApprovalPage);
                //this.navCtrl.pop();
                this.app.getRootNav().setRoot(TabsPage);

            } else {
                this.toastResult('审核失败','退回失败');
            }
            this.showLoading(false,'正在处理中');
        }, error => {
            this.toastResult('审核失败','退回失败');
            this.showLoading(false,'正在处理中');

        })
    }
    zjspInfo(_v){
        this.showLoading(true,'正在处理中');
        let data: any = {
            YongHuBH: this.userId,
            ShenQingBMBH: this.branchId,
            BaoXiaoJE: this.detail.DanJuXX.JieKuanJE==''?'0':this.detail.DanJuXX.JieKuanJE,
            DanJuLX: this.detail.DanJuXX.JieKuanDLX,
            DanJuBH: this._d.BianHao,
            LiuChengId: this._d.LiuChengId,
            TaskId: this._d.RenWuID,
            DangQianJD: this._d.DangQianJD,
            Next: _v,
            ShenPiYJ: this.remarkVal,
            FileList: this.fileList[0],
            ShenPiYS: this.list,
            sign:this.hqId.toString()

        };
        this.sys.zjsqdbspApprove(data).subscribe((res: any) => {
            if (res.msgCode == '1') {
                this.toastResult('审核成功','退回成功');
                //this.app.getRootNav().setRoot(ToDoApprovalPage);
                this.app.getRootNav().setRoot(TabsPage);

                //this.navCtrl.pop();
            } else {
                this.toastResult('审核失败','退回失败');
            }
            this.showLoading(false,'正在处理中');
        }, error => {
            this.toastResult('审核失败','退回失败');
            this.showLoading(false,'正在处理中');

        })
    }
    zxspInfo(_v){
        this.showLoading(true,'正在处理中');
        let data: any = {
            YongHuBH: this.userId,
            ShenQingBMBH: this.branchId,
            BaoXiaoJE:this.detail.DanJuXX.ShenQingJE==''?'0':this.detail.DanJuXX.ShenQingJE,
            DanJuBH: this._d.BianHao,
            LiuChengId: this._d.LiuChengId,
            TaskId: this._d.RenWuID,
            DangQianJD: this._d.DangQianJD,
            Next: _v,
            ShenPiYJ: this.remarkVal,
            FileList: this.fileList[0],
            ShenPiYS: this.list,
            sign:this.hqId.toString(),
            ShiFouZFCG:this.ShiFouZFCG,
            CaiGouLX:this.CaiGouLX,
            CaiGouFS:this.CaiGouFS,
            ShiFouCGJH:this.ShiFouCGJH,
            ZuZhiXS:this.ZuZhiXS,
            ShiFouQDHT:this.ShiFouQDHT,
            ShiFouKN:this.ShiFouKN,
            ShiFouCGXG:this.ShiFouCGXG
        };
        this.sys.zxsqdbspApprove(data).subscribe((res: any) => {
            if (res.msgCode == '1') {
                this.toastResult('审核成功','退回成功');
                this.app.getRootNav().setRoot(TabsPage);
            } else {
                this.toastResult('审核失败','退回失败');
            }
            this.showLoading(false,'正在处理中');
        }, error => {
            this.toastResult('审核失败','退回失败');
            this.showLoading(false,'正在处理中');

        })
    }
    toastResult(str1,str2){
         if(this.way =='pass'){
             this.showToast(str1);
         } else {
             this.showToast(str2);
         }
    }
    presentActionSheet() {
        let actionSheet = this.actionSheetCtrl.create({
            buttons: [{
                text: '拍照',
                role: 'takePhoto',
                handler: () => {
                    this.takePhoto();
                }
            }, {
                text: '从相册选择',
                role: 'chooseFromAlbum',
                handler: () => {
                    this.chooseFromAlbum();
                }
            }, {
                text: '取消',
                role: 'cancel',
                handler: () => {
                }
            }]
        });

        actionSheet.present().then(value => {
            return value;
        });
    }

    takePhoto() {
        const options: CameraOptions = {
            targetWidth: 800,
            targetHeight: 800,
            saveToPhotoAlbum: true,
            quality: 50,//图片的质量0-100之间选择
            sourceType: this.camera.PictureSourceType.CAMERA,
            destinationType: this.camera.DestinationType.DATA_URL,
        };

        this.camera.getPicture(options).then(image => {
            this.fuJianList.splice(0,this.fuJianList.length);
            // Log.printObj(ApprovePage.TAG, '相机拍照Image URI:== ', image);
            if(image !=undefined || null !=image){
                this.fuJianList.push({value: "data:image/jpeg;base64," + image});
                this.updateImgServer(this.fuJianList);
            }
        }, error => {
            Log.printObj(ZjApprovePage.TAG, '相机拍照ImageError:== ', error);
        });
    }

    chooseFromAlbum() {
        this.imagePicker.hasReadPermission().then(result=>{
            if(result){
                this.chooseImg();
            }else {
                this.showToast('没有权限访问你的相册');
            }
        });
    }
    chooseImg(){
        this.fuJianList=[];
        const options:ImagePickerOptions = {
            maximumImagesCount: 1,
            width: 800,
            height: 800,
            outputType: 1,
            quality: 50
        };
        this.imagePicker.getPictures(options).then( DATA_URL => {
            if (DATA_URL.length > 1) {
                this.presentAlert();
            } else if (DATA_URL.length == 1) {
                for (let i = 0; i < DATA_URL.length; i++) {
                    this.fuJianList.push({value: "data:image/jpeg;base64," + DATA_URL[i]});
                }
                this.updateImgServer(this.fuJianList);
            }
        }, error => {
            Log.printObj(ZjApprovePage.TAG, '选择相册图片ImageError:== ', error);

        });
    }
    presentAlert() {
        let alert = this.alertCtrl.create({title: "上传失败", message: "最多选择1张图片", buttons: ["确定"]});
        alert.present().then(value => {
            return value;
        });
    }

    indexToVal(arr,id){

      return  arr.filter(item=>item.BianMa ==id)

    }
    CaiGouLXHander() {
        if(this.ShiFouCGXG==0) return
        console.log(this.cglxlist.some(u => u.BianMa == this.CaiGouLX ))
        let alert = this.alertCtrl.create();
        alert.setTitle('采购类型');
        this.cglxlist.forEach((value, index) => {
            alert.addInput({
                type: 'radio',
                label: value.Zhi,
                value: value.BianMa,
                checked:this.CaiGouLX == value.BianMa? true : false
            });
        });

        alert.addButton('取消');
        alert.addButton({
            text: '确定',
            handler: data => {
                console.log(data,"=====");
                this.CaiGouLX = data;
                this.cglxlist.forEach((v, i) => {
                    if (data == v.BianMa) {
                        this.CaiGouLXLabel =v.Zhi;
                    }
                });
            }
        });
        alert.present();
    }
    CaiGouFSHander() {
        if(this.ShiFouCGXG==0) return
        let alert = this.alertCtrl.create();
        alert.setTitle('采购方式');
        this.cgfslist.forEach((value, index) => {
            alert.addInput({
                type: 'radio',
                label: value.Zhi,
                value: value.BianMa,
                checked:this.CaiGouFS == value.BianMa? true : false


            });
        });

        alert.addButton('取消');
        alert.addButton({
            text: '确定',
            handler: data => {
                console.log(data,"=====");
                this.cgfslist.forEach((v, i) => {
                    if (data == v.BianMa) {
                        this.CaiGouFSLabel =v.Zhi;
                        this.CaiGouFS = data;
                    }
                });
            }
        });
        alert.present();
    }
    CaiGouZZXSHander() {
        if(this.ShiFouCGXG==0) return
        let alert = this.alertCtrl.create();
        alert.setTitle('组织形式');
        this.zzxslist.forEach((value, index) => {
            alert.addInput({
                type: 'radio',
                label: value.Zhi,
                value: value.BianMa,
                checked:this.ZuZhiXS == value.BianMa? true : false

            });
        });

        alert.addButton('取消');
        alert.addButton({
            text: '确定',
            handler: data => {
                console.log(data,"=====");
                this.zzxslist.forEach((v, i) => {
                    if (data == v.BianMa) {
                        this.ZuZhiXS = data;
                        this.ZuZhiXSLabel =v.Zhi;
                    }
                });
            }
        });
        alert.present();
    }
    sflistHandler(title,type,val){
        if(this.ShiFouCGXG==0) return
        let alert = this.alertCtrl.create();
        alert.setTitle(title);
        this.sflist.forEach((value, index) => {
            alert.addInput({
                type: 'radio',
                label: value.Zhi,
                value: value.BianMa,
                checked:val == value.BianMa? true : false
            });
        });

        alert.addButton('取消');
        alert.addButton({
            text: '确定',
            handler: data => {
                console.log(data,"=====");
                this.sflist.forEach((v, i) => {
                    if (data == v.BianMa) {

                        if(type ==0){
                            this.ShiFouCGJH = data;
                            this.ShiFouCGJHLabel = v.Zhi;
                        }else if(type ==1){
                            this.ShiFouZFCG = data;
                            this.ShiFouZFCGLabel = v.Zhi;
                        }else if(type ==2){
                            this.ShiFouQDHT = data;
                            this.ShiFouQDHTLabel = v.Zhi;
                        }else if(type ==3){
                            this.ShiFouKN = data;
                            console.log( v.Zhi)
                            this.ShiFouKNLabel = v.Zhi;
                        }


                    }
                });
            }
        });
        alert.present();
    }
    approverHander() {
        let alert = this.alertCtrl.create();
        alert.setTitle('会签人');
        this.approveList.forEach((value, index) => {
            alert.addInput({
                type: 'checkbox',
                label: value.YongHuXM,
                value: value.YongHuBH,
                checked:  this.hqId.includes(value.YongHuBH)
            });
        });

        alert.addButton('取消');
        alert.addButton({
            text: '确定',
            handler: data => {
                console.log(data,"=====");
                this.hqName ='';
                this.hqId =[];
                this.approveList.forEach((v, i) => {
                    data.map(item=>{
                        if (item == v.YongHuBH) {
                            this.hqName += v.YongHuXM+' ';
                            this.hqId.push(v.YongHuBH);
                            console.log(item)
                        }
                    })

                });
            }
        });
        alert.present();
    }
    updateImgServer(data) {
        this.sys.getFileUpload(data).subscribe((res: any) => {
            Log.printObj(ZjApprovePage.TAG,"上传附件接口result==",res);
            if (res.msgCode == "1" && res.list.length>0) {
                this.fileList=res.list;
                this.showToast("上传成功");
            } else {
                //this.showError("上传失败");
            }
        }, error => {
            this.showError("上传失败");
            Log.printObj(ZjApprovePage.TAG,"上传附件接口 error result==",error);

        })
    }
    stringify(wordArray) {
        // Shortcuts
        var words = wordArray.words;
        var sigBytes = wordArray.sigBytes;

        // Convert
        var u8 = new Uint8Array(sigBytes);
        for (var i = 0; i < sigBytes; i++) {
            var byte = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
            u8[i] = byte;
        }
        return u8;
    }

    getBuffer(blob){
        return new Promise((resolve, reject)=>{
            var arrayBuffer;
            var fileReader = new FileReader();
            fileReader.onload = function() {
                arrayBuffer = this.result;
                resolve(arrayBuffer);
            };
            fileReader.readAsArrayBuffer(blob);
        });
    }
}
